package com.hdax.dmw.scheduler.listener;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.hdax.dmw.entity.scheduler.DmSchedulerSeat;
import com.hdax.dmw.entity.scheduler.TxMsg;
import com.hdax.dmw.exceptions.order.OrderException;
import com.hdax.dmw.scheduler.service.DmSchedulerSeatService;
import com.hdax.dmw.scheduler.service.TxMsgService;
import com.hdax.dmw.utils.ServiceResultEnum;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@RabbitListener(queues = "order_tx_queue")
public class TxMsgListener {

    @Autowired
    private DmSchedulerSeatService seatService;
    @Autowired
    private TxMsgService txMsgService;

    @RabbitHandler
    @Transactional
    public void changeSeat(Channel channel, Message message, String msg){
        TxMsg txMsg = JSONUtil.toBean(msg, TxMsg.class);
        txMsgService.save(txMsg);
        Map<String,Object> map = JSONUtil.toBean(txMsg.getMsg(), Map.class);
        String[] linkIds = ((JSONArray) map.get("linkIds")).toArray(new String[0]);
        String[] seatPositions = ((JSONArray) map.get("seatPositions")).toArray(new String[0]);
        //每一个要修改的座位信息
        List<DmSchedulerSeat> seats = new ArrayList<>();
        for (int i = 0; i < seatPositions.length; i++) {
            String seatString = seatPositions[i];
            Integer x = Integer.parseInt(seatString.split("_")[0]);
            Integer y = Integer.parseInt(seatString.split("_")[1]);
            Long schedulerId = Long.parseLong(map.get("scheduleId").toString());
            DmSchedulerSeat seat = seatService.detail(schedulerId, x, y);
            if(seat.getOrderNo()!=null &&
                    seat.getUserId()!=null && seat.getStatus()!=1){
                ServiceResultEnum resultEnum = ServiceResultEnum.ORDER_SEAT_LOCK;
                throw new OrderException(resultEnum.getCode(),resultEnum.getResult());
            }
            seat.setOrderNo(map.get("orderNo").toString());
            seat.setUserId(Long.parseLong(map.get("userId").toString()));
            seat.setStatus(2);
            seats.add(seat);
        }
        seatService.updateBatchById(seats);
        txMsg.setVersion(txMsg.getVersion()+1);
        txMsg.setMsg_result("1");
        txMsgService.updateById(txMsg);
    }
}
